package com.heima.search.listener;

import com.alibaba.fastjson.JSONObject;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.search.dtos.SearchArticleVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void getMessage(String message){
        //1.解析成对象
        SearchArticleVo vo = JSONObject.parseObject(message, SearchArticleVo.class);
        //2.新增数据到ES中
        IndexRequest indexRequest=new IndexRequest("app_info_article").id(vo.getId().toString());
        indexRequest.source(message, XContentType.JSON);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
